﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Civic.Platform.Teach.Service.API
{
    public class ZjApiUtil
    {
        //public static string token = "d8df1080-b867-4921-b3e2-5786c7cc2566";
        //public static string cid = "eb878cb8-4ba2-4c24-bc23-f8c5406337bc";
        //public static String appSecret = "52be15f0-a154-48ca-9f0d-ce01a5ca8e1d";
        //public static String user = "a5fdfd0e-ad29-4c3e-8d30-77c9d9ae41fc";
        //public static String pwd = "g6519K6Nar5vM72U046d18TCp4C753";

        public static string url = "https://openapi-test.sinoiov.cn";
        //public static string url = "https://zhiyunopenapi.95155.com";
        public static string token = "";
        public static string cid = "2ba30b92-c5a6-495e-bb8b-63da31b51da3";
        public static string appSecret = "6dc2db6a-8328-4aa4-9324-b2843a806b87";
        public static string user = "85e6da20-3823-4aba-a577-8d96c52d9e11";
        public static string pwd = "1482TxT860Vm0M201XbbcU3v1YpX7o";
        /**
*	获取签名
*	@param paramDic	API请求参数，以Map<String,String>类型
*	@param appSecret	用户私钥
*	@return
*	签名
*/
        public static String sign(Dictionary<String, String> paramDic, String appSecret)
        {
            byte[] signatureKey = Encoding.UTF8.GetBytes(appSecret);
            //第一步：拼装key+value
            List<String> list = new List<String>();
            foreach (KeyValuePair<String, String> kv in paramDic)

            {
                list.Add(kv.Key + kv.Value);
            }
            //第二步：排序
            list.Sort();
            //第三步：拼装排序后的各个字符串
            String tmp = "";
            foreach (String kvstr in list)
            {
                tmp = tmp + kvstr;
            }
            //第四步：将拼装后的字符串和app密钥一起计算签名
            //HMAC-SHA1
            HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey); hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp)); byte[] hash = hmacsha1.Hash;
            //TO HEX
            return BitConverter.ToString(hash).Replace("-", String.Empty).ToUpper();
        }
        /**
*	现API登录调用方式
*/
        public static void loginDemo()
        {
            try
            {
                // 请 求
                Dictionary<String, String> map = new Dictionary<String, String>(4);
                // 账 号
                map.Add("user", user);
                // 密 码
                map.Add("pwd", pwd);
                // 客户端id
                map.Add("cid", cid);

                // url地址 //登录接口为login
                String url = "https://openapi-test.sinoiov.cn/save/apis/login/";
                //String url = "https://zhiyunopenapi.95155.com/save/apis/login/";
                // 用户私钥

                // String appSecret = "52be15f0-a154-48ca-9f0d-ce01a5ca8e1d";
                // 调用工具类获取签名
                String sign1 = sign(map, appSecret);
                map.Add("sign", sign1);
                // 以POST方式请求开放平台获取token
                String result = post(url, map);
                Dictionary<String, Object> jsonDict = JsonConvert.DeserializeObject<Dictionary<String, Object>>(result);
                string data = jsonDict["result"].ToString();
                token = data;// (string)(JsonConvert.DeserializeObject(result));
                //System.out.println("返回token:" + result);
                //  ShowNotify("返回token:" + result);
            }
            catch (Exception e)
            {
                //ShowNotify(e.Message);
            }
        }


        public static string loginDemoE()
        {
            try
            {
                // 请 求
                Dictionary<String, String> map = new Dictionary<String, String>(4);
                // 账 号
                map.Add("user", user);
                // 密 码
                map.Add("pwd", pwd);
                // 客户端id
                map.Add("cid", cid);

                // url地址 //登录接口为login
                String url = "https://openapi-test.sinoiov.cn/save/apis/login/";
                //String url = "https://zhiyunopenapi.95155.com/save/apis/login/";
                // 用户私钥

                // String appSecret = "52be15f0-a154-48ca-9f0d-ce01a5ca8e1d";
                // 调用工具类获取签名
                String sign1 = sign(map, appSecret);
                map.Add("sign", sign1);
                // 以POST方式请求开放平台获取token
                String result = post(url, map);
                Dictionary<String, Object> jsonDict = JsonConvert.DeserializeObject<Dictionary<String, Object>>(result);
                if (jsonDict["result"]!= null)
                {
                    string data = jsonDict["result"].ToString();
                    token = data;// (string)(JsonConvert.DeserializeObject(result));
                    return token.ToString();

                }
                else
                {
                    string msg = jsonDict["status"].ToString();
                    return msg;
                }

                //System.out.println("返回token:" + result);
                //  ShowNotify("返回token:" + result);
            }
            catch (Exception e)
            {

                throw e;
            }
                

        }
        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string post(string url, Dictionary<string, string> dic)
        {
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">请求的servlet地址，不带参数</param>
        /// <param name="postData"></param>
        /// <returns>请求的参数，key=value&key1=value1</returns>
        public static string post(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            SetHeaderValue(request.Headers, "Content-Type", "application/json");
            SetHeaderValue(request.Headers, "Accept", "application/json");
            SetHeaderValue(request.Headers, "Accept-Charset", "utf-8");
            request.Method = "POST";
            request.Timeout = 300000;

            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
            string result = reader.ReadToEnd();
            response.Close();
            return result;
        }
        public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property =
                typeof(WebHeaderCollection).GetProperty("InnerCollection",
                    BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                if (property.GetValue(header, null) is NameValueCollection collection) collection[name] = value;
            }
        }

        //public class LES_ZJ_CAR_POSITON
        //{
        //    /// <summary>
        //    /// 车牌号
        //    /// </summary>
        //    public string VNO { get; set; }
        //    /// <summary>
        //    /// 车牌颜色
        //    /// </summary>
        //    public string VCO { get; set; }
        //    /// <summary>
        //    /// 车辆定位时间
        //    /// </summary>
        //    public string UTC { get; set; }
        //    /// <summary>
        //    /// 车辆定位纬度
        //    /// </summary>
        //    /// 
        //    public string WL { get; set; }
        //    /// <summary>
        //    /// WL
        //    /// </summary>
        //    public string LAT { get; set; }
        //    /// <summary>
        //    /// 车辆定位经度
        //    /// </summary>
        //    public string LON { get; set; }
        //    /// <summary>
        //    /// 车辆地理位置名称
        //    /// </summary>
        //    public string ADR { get; set; }
        //    /// <summary>
        //    /// 速度单位 km/h
        //    /// </summary>
        //    public string SPD { get; set; }
        //    /// <summary>
        //    /// 方向
        //    /// </summary>
        //    public string DRC { get; set; }
        //    /// <summary>
        //    /// 省
        //    /// </summary>
        //    public string PROVINCE { get; set; }
        //    /// <summary>
        //    /// 市
        //    /// </summary>
        //    public string CITY { get; set; }
        //    /// <summary>
        //    /// 县
        //    /// </summary>
        //    public string COUNTRY { get; set; }
        //    /// <summary>
        //    /// 里程(百米)
        //    /// </summary>
        //    public string MIL { get; set; }
        //    /// <summary>
        //    /// 查询状态码
        //    /// </summary>
        //    public string STATE { get; set; }
        //    /// <summary>
        //    /// 备注
        //    /// </summary>
        //    public string MEMO { get; set; }
        //    /// <summary>
        //    /// 插入时间
        //    /// </summary>
        //    public DateTime? INS_TIME { get; set; }
        //    /// <summary>
        //    /// 录入人
        //    /// </summary>
        //    public string INS_EMP_ID { get; set; }
        //    /// <summary>
        //    /// 修改时间
        //    /// </summary>
        //    public DateTime? MOD_TIME { get; set; }
        //    /// <summary>
        //    /// 修改人
        //    /// </summary>
        //    public string MOD_EMP_ID { get; set; }
        //    /// <summary>
        //    /// 修改程序
        //    /// </summary>
        //    public string MOD_PGM_ID { get; set; }
        //}
    }
}

